package com.pactera.madp.cp.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.cp.api.entity.CorpEntity;
import com.pactera.madp.cp.api.entity.WorkContactRoomEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.WorkRoomEntity;
import com.pactera.madp.cp.api.model.workroom.WXWorkRoomIdsModel;
import com.pactera.madp.cp.api.model.workroom.WXWorkRoomInfoModel;
import com.pactera.madp.cp.api.model.workroom.WXWorkRoomModel;
import com.pactera.madp.cp.common.util.DateUtils;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.pactera.madp.cp.common.constant.WxCallbackConst.*;

/**
 * @description:
 * @author: Huayu
 * @time: 2020/12/21 9:40
 */
@Service
@Slf4j
public class WxCallbackChatServiceImpl implements IWxCallbackChatService {

    @Autowired
    private ICorpService corpServiceImpl;
    @Autowired
    private IWorkRoomService workRoomServiceImpl;
    @Autowired
    private IWorkContactRoomService workContactRoomService;
    @Autowired
    private IWorkEmployeeService employeeService;

    @Override
    public String dispatchEvent(String dataJson) {
        JSONObject jsonObject = JSON.parseObject(dataJson);
        JSONObject xmlJsonObject = jsonObject.getJSONObject("xml");
        log.info("xmlJsonObject"+xmlJsonObject);
        String changeType =  xmlJsonObject.getString("changetype");
        String updateDetail = xmlJsonObject.getString("updatedetail");
        if (DISMISS.equals(changeType)) {
            String chatid = xmlJsonObject.getString("chatid");
            WorkRoomEntity one = workRoomServiceImpl.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                    .eq(WorkRoomEntity::getWxChatId, chatid));
            WorkRoomEntity entity = new WorkRoomEntity();
            entity.setRoomStatus(1);
            entity.setDismissTime(LocalDateTime.now());
            entity.setId(one.getId());
            workRoomServiceImpl.updateById(entity);
            return "success";
        }
        if (UPDATE.equals(changeType) && UPDATE_DETAIL_CHANGE_OWNER.equals(updateDetail)) {
            String wxCorpId = xmlJsonObject.getString("tousername");
            String chatId = xmlJsonObject.getString("chatid");
            List<CorpEntity> list = corpServiceImpl.list(Wrappers.<CorpEntity>lambdaQuery().eq(CorpEntity::getWxCorpId, wxCorpId));
            CorpEntity entity = list.get(0);
            if (chatId != null || !chatId.equals("")) {
                WorkRoomEntity room = workRoomServiceImpl.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                        .eq(WorkRoomEntity::getWxChatId, chatId));
                WorkContactRoomEntity contactRoom = new WorkContactRoomEntity();
                LambdaUpdateWrapper<WorkContactRoomEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(WorkContactRoomEntity::getRoomId,room.getId());
                updateWrapper.eq(WorkContactRoomEntity::getEmployeeId,room.getOwnerId());
                contactRoom.setStatus(2);
                //更新成员为退群状态
                boolean flag1 = workContactRoomService.update(contactRoom, updateWrapper);
                //获取群聊详情
                entity.setWxCorpId(wxCorpId);
                log.info("corpEntity为："+entity);
                String workRoomInfo = WxApiUtils.getWorkRoomInfoData(entity,chatId);
                log.info("workRoomInfo为："+workRoomInfo);
                JSONObject workRoomInfoJson = JSONObject.parseObject(workRoomInfo);
                String ownerId = workRoomInfoJson.get("owner").toString();
                WorkEmployeeEntity employee = employeeService.getOne(new LambdaQueryWrapper<WorkEmployeeEntity>()
                        .eq(WorkEmployeeEntity::getWxUserId, ownerId));
                room.setOwnerId(employee.getId());
                //更新ownerId
                boolean flag2 = workRoomServiceImpl.updateById(room);
                if (!flag1 && !flag2) {
                    throw new IllegalArgumentException("群主变更回调更新失败");
                }
            }
            return "success";
        }
        String wxCorpId = xmlJsonObject.getString("tousername");
        log.info("wxCorpId为：" +wxCorpId);
        String chatId = xmlJsonObject.getString("chatid");
        log.info("chatId为：" + chatId);
        List<CorpEntity> list = corpServiceImpl.list(Wrappers.<CorpEntity>lambdaQuery().eq(CorpEntity::getWxCorpId, wxCorpId));
        CorpEntity entity = list.get(0);
        log.info("corpEntity外  为："+entity);
        if(chatId != null || !chatId.equals("")){
            //获取群聊详情
            entity.setWxCorpId(wxCorpId);
            log.info("corpEntity内  为："+entity);
            String workRoomInfo = WxApiUtils.getWorkRoomInfoData(entity,chatId);
            log.info("workRoomInfo为："+workRoomInfo);
            JSONObject workRoomInfoJson = JSONObject.parseObject(workRoomInfo);
            String ownerId = workRoomInfoJson.get("owner").toString();
            //List<WXWorkRoomInfoModel> resultInfoList = jsonArray.toJavaList(WXWorkRoomInfoModel.class);
            //获取客户群列表
            String workRoomIndexData = WxApiUtils.getWorkRoomIndexData(entity,ownerId);
            List<WXWorkRoomIdsModel> workRoomIdsModelList = JSONArray.parseArray(workRoomIndexData, WXWorkRoomIdsModel.class);
            log.info("workRoomIdsModelList:{}",workRoomIdsModelList);
            List<WXWorkRoomModel> WXWorkRoomModelList = new ArrayList<WXWorkRoomModel>();
            for (WXWorkRoomIdsModel workRoomIdsModel:
                    workRoomIdsModelList) {
                WXWorkRoomModel WXWorkRoomModel = new WXWorkRoomModel();
                WXWorkRoomModel.setChatId(workRoomIdsModel.getChatId());
                WXWorkRoomModel.setStatus(workRoomIdsModel.getStatus());
                //获取群聊详情
                String workRoomInfoData = WxApiUtils.getWorkRoomInfoData(entity,workRoomIdsModel.getChatId());
                //合并客户群和客户群详情数据
                //取出member_list
                JSONObject workRoomInfoJsonData = JSONObject.parseObject(workRoomInfoData);
                WXWorkRoomModel.setName(workRoomInfoJsonData.get("name").toString());
                WXWorkRoomModel.setOwner(workRoomInfoJsonData.get("owner").toString());
                DateTime time = DateTime.of(workRoomInfoJsonData.getLong("create_time")*1000);
                log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                log.info("createTime: "+DateUtils.asLocalDateTime(time));
                log.info("time: "+time);
                log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                WXWorkRoomModel.setCreateTime(DateUtils.asLocalDateTime(time));
                String notice = workRoomInfoJsonData.getString("notice");
                if (!StringUtil.isBlank(notice)){
                    WXWorkRoomModel.setNotice(notice);
                }
                JSONArray jsonArray= workRoomInfoJsonData.getJSONArray("member_list");
                List<WXWorkRoomInfoModel> resultInfoList = jsonArray.toJavaList(WXWorkRoomInfoModel.class);
                log.info("resultInfoList为："+resultInfoList);
                WXWorkRoomModel.setWXWorkRoomInfoModel(resultInfoList);
                WXWorkRoomModelList.add(WXWorkRoomModel);
            }
            log.info("WXWorkRoomModelList为："+WXWorkRoomModelList);
            //查询企业授信信息
            if(entity != null){
                try {
                    workRoomServiceImpl.syncWorkRoomIndex(entity.getCorpId(),WXWorkRoomModelList,1);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return "success";
    }

    @Override
    public String updateChatCallBack(String dataJson){
        JSONObject jsonObject = JSON.parseObject(dataJson);
        JSONObject xmlJsonObject = jsonObject.getJSONObject("xml");
        log.info("xmlJsonObject"+xmlJsonObject);
        String changeType = xmlJsonObject.getString("changetype");
        String updateDetail = xmlJsonObject.getString("updatedetail");
        if (DISMISS.equals(changeType)){
            String chatid = xmlJsonObject.getString("chatid");
            WorkRoomEntity one = workRoomServiceImpl.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                    .eq(WorkRoomEntity::getWxChatId, chatid));
            WorkRoomEntity entity = new WorkRoomEntity();
            entity.setRoomStatus(1);
            entity.setDismissTime(LocalDateTime.now());
            entity.setId(one.getId());
            workRoomServiceImpl.updateById(entity);
        } else if (UPDATE.equals(changeType) && UPDATE_DETAIL_CHANGE_OWNER.equals(updateDetail)) {
            String wxCorpId = xmlJsonObject.getString("tousername");
            String chatId = xmlJsonObject.getString("chatid");
            List<CorpEntity> list = corpServiceImpl.list(Wrappers.<CorpEntity>lambdaQuery().eq(CorpEntity::getWxCorpId, wxCorpId));
            CorpEntity entity = list.get(0);
            if (chatId != null || !chatId.equals("")) {
                WorkRoomEntity room = workRoomServiceImpl.getOne(Wrappers.<WorkRoomEntity>lambdaQuery()
                        .eq(WorkRoomEntity::getWxChatId, chatId));
                WorkContactRoomEntity contactRoom = new WorkContactRoomEntity();
                LambdaUpdateWrapper<WorkContactRoomEntity> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(WorkContactRoomEntity::getRoomId,room.getId());
                updateWrapper.eq(WorkContactRoomEntity::getEmployeeId,room.getOwnerId());
                contactRoom.setStatus(2);
                //更新成员为退群状态
                boolean flag1 = workContactRoomService.update(contactRoom, updateWrapper);
                //获取群聊详情
                entity.setWxCorpId(wxCorpId);
                log.info("corpEntity为："+entity);
                String workRoomInfo = WxApiUtils.getWorkRoomInfoData(entity,chatId);
                log.info("workRoomInfo为："+workRoomInfo);
                JSONObject workRoomInfoJson = JSONObject.parseObject(workRoomInfo);
                String ownerId = workRoomInfoJson.get("owner").toString();
                WorkEmployeeEntity employee = employeeService.getOne(new LambdaQueryWrapper<WorkEmployeeEntity>()
                        .eq(WorkEmployeeEntity::getWxUserId, ownerId));
                room.setOwnerId(employee.getId());
                //更新ownerId
                boolean flag2 = workRoomServiceImpl.updateById(room);
                if (!flag1 && !flag2) {
                    throw new IllegalArgumentException("群主变更回调更新失败");
                }
            }


        } else {
            String wxCorpId = xmlJsonObject.getString("tousername");
            log.info("wxCorpId为：" +wxCorpId);
            String chatId = xmlJsonObject.getString("chatid");
            log.info("chatId为：" + chatId);
            List<CorpEntity> list = corpServiceImpl.list(Wrappers.<CorpEntity>lambdaQuery().eq(CorpEntity::getWxCorpId, wxCorpId));
            CorpEntity entity = list.get(0);
            log.info("corpEntity外  为："+entity);
            if(chatId != null || !chatId.equals("")){
                //获取群聊详情
                entity.setWxCorpId(wxCorpId);
                log.info("corpEntity内  为："+entity);
                String workRoomInfo = WxApiUtils.getWorkRoomInfoData(entity,chatId);
                log.info("workRoomInfo为："+workRoomInfo);
                JSONObject workRoomInfoJson = JSONObject.parseObject(workRoomInfo);
                String ownerId = workRoomInfoJson.get("owner").toString();
                //List<WXWorkRoomInfoModel> resultInfoList = jsonArray.toJavaList(WXWorkRoomInfoModel.class);
                //获取客户群列表
                String workRoomIndexData = WxApiUtils.getWorkRoomIndexData(entity,ownerId);
                List<WXWorkRoomIdsModel> workRoomIdsModelList = JSONArray.parseArray(workRoomIndexData, WXWorkRoomIdsModel.class);
                log.info("workRoomIdsModelList:{}",workRoomIdsModelList);
                List<WXWorkRoomModel> WXWorkRoomModelList = new ArrayList<WXWorkRoomModel>();
                for (WXWorkRoomIdsModel workRoomIdsModel:
                        workRoomIdsModelList) {
                    WXWorkRoomModel WXWorkRoomModel = new WXWorkRoomModel();
                    WXWorkRoomModel.setChatId(workRoomIdsModel.getChatId());
                    WXWorkRoomModel.setStatus(workRoomIdsModel.getStatus());
                    //获取群聊详情
                    String workRoomInfoData = WxApiUtils.getWorkRoomInfoData(entity,workRoomIdsModel.getChatId());
                    //合并客户群和客户群详情数据
                    //取出member_list
                    JSONObject workRoomInfoJsonData = JSONObject.parseObject(workRoomInfoData);
                    WXWorkRoomModel.setName(workRoomInfoJsonData.get("name").toString());
                    WXWorkRoomModel.setOwner(workRoomInfoJsonData.get("owner").toString());
                    DateTime time = DateTime.of(workRoomInfoJsonData.getLong("create_time")*1000);
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    log.info("createTime: "+DateUtils.asLocalDateTime(time));
                    log.info("time: "+time);
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                    WXWorkRoomModel.setCreateTime(DateUtils.asLocalDateTime(time));
                    String notice = workRoomInfoJsonData.getString("notice");
                    if (!StringUtil.isBlank(notice)){
                        WXWorkRoomModel.setNotice(notice);
                    }
                    JSONArray jsonArray= workRoomInfoJsonData.getJSONArray("member_list");
                    List<WXWorkRoomInfoModel> resultInfoList = jsonArray.toJavaList(WXWorkRoomInfoModel.class);
                    log.info("resultInfoList为："+resultInfoList);
                    WXWorkRoomModel.setWXWorkRoomInfoModel(resultInfoList);
                    WXWorkRoomModelList.add(WXWorkRoomModel);
                }
                log.info("WXWorkRoomModelList为："+WXWorkRoomModelList);
                //查询企业授信信息
                if(entity != null){
                    try {
                        workRoomServiceImpl.syncWorkRoomIndex(entity.getCorpId(),WXWorkRoomModelList,1);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "success";
    }
}
